package com.rookie.tool.module.util.ai.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author rookie
 */
@Slf4j
public class AiUtils {


    public static HttpEntity<byte[]> appendParam(String filePath, String paramName) {
        if (paramName == null) {
            paramName = "image=";
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/x-www-form-urlencoded");
        String base64Img = getBase64Img(filePath);
        return new HttpEntity<>((paramName + base64Img).getBytes(StandardCharsets.UTF_8), httpHeaders);
    }

    /**
     * 获取图片base64编码
     *
     * @param filePath 图片本地路径
     * @return base64编码
     */
    public static String getBase64Img(String filePath) {
        try {
            byte[] imgBytes = FileUtil.readFileByBytes(filePath);
            String imgBase = Base64.getEncoder().encodeToString(imgBytes);
            return URLEncoder.encode(imgBase, "UTF-8");
        } catch (IOException e) {
            log.error("读取图片失败");
        }
        return null;
    }
}
